package micro

import (
	"cdzhmc.com/go-mc/micro/client"
	"cdzhmc.com/go-mc/micro/config/cmd"
	"cdzhmc.com/go-mc/micro/plugin"
	"cdzhmc.com/go-mc/micro/server"
	"log"
	"os"
	"strings"
	"sync"
)

type service struct {
	opts Options
	once sync.Once
}

func newService(opts ...Option) Service {
	service := new(service)
	options := newOptions(opts...)
	service.opts = options
	return service
}

func (s *service) Name() string {
	panic("implement me")
}

func (s *service) Init(opts ...Option) {
	for _, o := range opts {
		o(&s.opts)
	}
	s.once.Do(func() {
		for _, p := range strings.Split(os.Getenv("MICRO_PLUGIN"), ",") {
			if len(p) == 0 {
				continue
			}
			// load the plugin
			c, err := plugin.Load(p)
			if err != nil {
				log.Fatal(err)
			}
			// initialise the plugin
			if err := plugin.Init(c); err != nil {
				log.Fatal(err)
			}
		}
		// set cmd name
		//if len(s.opts.Cmd.App().Name) == 0 {
		//	s.opts.Cmd.App().Name = s.Server().Options().Name
		//}
		if err := s.opts.Cmd.Init(
			cmd.Broker(&s.opts.Broker),

			);err!=nil {
			log.Fatal(err)
		}
	})
}

func (s *service) Options() Options {
	return s.opts
}

func (s *service) Client() client.Client {
	return s.opts.Client
}

func (s *service) Server() server.Server {
	return s.opts.Server
}

func (s *service) Run() error {

}

func (s *service) String() string {
	return "micro"
}

